import Taro from "@tarojs/taro";
import { ReactNode, useId } from "react";
import { Canvas, View } from "@tarojs/components";
import useMask from "@/hooks/useMask";
import { useMount } from "ahooks";

import ByText from "../ui/ByText";
import BySquare from "../ui/BySquare";
import useUpload from "@/hooks/useUpload";

type UploaderProps = {
  count?: number;
  action?: string;

  error?: string;
  size?: number;
  disabled?: boolean;
  children?: ReactNode;

  openWatermask?: boolean;
  customerName?: string;

  onClick?: () => void;
  onSuccess?: (event: string[]) => void;
};

export default ({
  count = 9,
  disabled,
  size = 140,
  error,
  children,

  openWatermask = true,

  onSuccess,
}: UploaderProps) => {
  const { upload } = useUpload({ onSuccess });

  const id = useId();
  const nodeId = `imageMask_` + id;

  const { canvasRef, batchDrawImage } = useMask();

  const chooseMedia = async () => {
    const { tapIndex } = await Taro.showActionSheet({
      itemList: ["拍照", "从相册选择"],
    });

    const { tempFiles } = await Taro.chooseMedia({
      count,
      sourceType: tapIndex === 0 ? ["camera"] : ["album"],
      mediaType: ["image"],
      // 开启压缩
      sizeType: ["compressed"],
    });

    let pathList = tempFiles.map(({ tempFilePath }) => tempFilePath);

    if (openWatermask && tapIndex === 0) {
      pathList = await batchDrawImage(pathList);
    }

    upload(pathList);
  };

  useMount(() => {
    if (openWatermask) {
      Taro.createSelectorQuery()
        .select("#" + nodeId)
        .fields({ node: true, size: true })
        .exec((res) => {
          canvasRef.current = res[0].node;
        });
    }
  });

  return (
    <>
      <BySquare
        icon="Plus"
        className={`border-third border-dashed bg-[#f1f1f1] text-third ${
          !children && "border-1"
        }`}
        circle={false}
        size={size}
        onClick={() => !disabled && chooseMedia()}
      >
        {children ??
          (disabled && error && (
            <View className="text-center">
              <ByText size="xs" type="third">
                {error}
              </ByText>
            </View>
          ))}
      </BySquare>

      {openWatermask && (
        <View className="fixed bottom-0 left-0 w-[0] h-[0] zIndex-[0] -translate-y-full -translate-x-full">
          <Canvas type="2d" id={nodeId} />
        </View>
      )}
    </>
  );
};
